package com.test.demo.security.oauth;

import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/oauth")
public class CustomTokenEndPoint {
//    @Override
//    public ResponseEntity<OAuth2AccessToken> postAccessToken(
//            Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
//        // 自定义逻辑
//        return super.postAccessToken(principal, parameters);
//    }

    @PostMapping("/token")
    public ResponseEntity<OAuth2AccessToken> test(Principal principal, @RequestParam Map<String, String> parameters) {
        if (principal instanceof Authentication) {
            Authentication authentication = (Authentication) principal;
            String userName = authentication.getName();
            String password = (String) authentication.getPrincipal();
            System.out.println("username: " + userName + "poassword: " + password);

            String token = "dsaiofhaohdfiasjdfioa";
            Map<String, String> map = new HashMap<>();
            map.put(DefaultOAuth2AccessToken.ACCESS_TOKEN, token);
            OAuth2AccessToken accessToken = DefaultOAuth2AccessToken.valueOf(map);

            return ResponseEntity.ok(accessToken);
        }

        return null;
    }

}
